//
//  HTChangeTruckViewController.m
//  TruckDriver
//
//  Created by Ting Han on 2017/9/26.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTChangeTruckViewController.h"
#import "HTNormalCell.h"
#import "HTCommitView.h"
#import "HTVoiceRemindCell.h"
#import "UIView+Layout.h"

#import "HTNormalTitleCell.h"

#import "HTNormalModel.h"
#import "HTNormalTitleModel.h"

#import "HTInputViewController.h"
#import "HTChoseViewController.h"
#import "UIImageView+WebCache.h"

//车牌号
#import "HTTruckLicenseView.h"
#import "HTMineViewController.h"

@interface HTChangeTruckViewController ()<UITableViewDelegate,UITableViewDataSource,HTChoseViewControllerDelegate,HTInputViewControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,HTTruckLicenseViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *safeBottomHeight;
@property (nonatomic,strong) NSArray *dataSource;
@property (nonatomic,weak) UIImageView *headImageView;

@property (nonatomic,strong) NSString *picurl;
@property (nonatomic,strong) NSString *license;
@property (nonatomic,strong) NSString *heavy;
@property (nonatomic,strong) NSString *truckType;
@property (nonatomic,strong) NSString *length;
@property (nonatomic,strong) NSString *cardType; //1 blue 2 yellow
@property (nonatomic,strong) NSString *isFollow;

@end


@implementation HTChangeTruckViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"更换车辆";
    self.isFollow = @"1";
    self.safeBottomHeight.constant = IPHONE_SAFEBOTTOMAREA_HEIGHT; self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"HTNormalCell" bundle:nil] forCellReuseIdentifier:normalCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"HTVoiceRemindCell" bundle:nil] forCellReuseIdentifier:voiceCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"HTNormalTitleCell" bundle:nil] forCellReuseIdentifier:normalTitleCell];
    self.tableView.backgroundColor = kBackgroundColor;
    self.picurl = self.mineModel.license;
    self.cardType = self.mineModel.numbertype;
    self.truckType = self.mineModel.types;
    self.license = self.mineModel.carids;
    self.heavy = self.mineModel.loads;
    self.length = self.mineModel.length;
    self.dataSource = @[[HTNormalTitleModel normalModelWithTitle:@"车牌类型" detital: [self.mineModel.numbertype isEqualToString:@"1"] ? @"蓝色车牌":@"黄色车牌"]
                        ,[HTNormalTitleModel normalModelWithTitle:@"车牌号码" detital:self.mineModel.carids]
                        ,[HTNormalTitleModel normalModelWithTitle:@"车型" detital:self.mineModel.types]
                        ,[HTNormalTitleModel normalModelWithTitle:@"车长" detital: [NSString stringWithFormat:@"%@米",self.mineModel.length]]
                        ,[HTNormalTitleModel normalModelWithTitle:@"载重" detital: [NSString stringWithFormat:@"%@吨",self.mineModel.loads]]];
   
}

#pragma mark --- tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return self.dataSource.count;
    }else if (section == 1){
        return 1;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:
            return 50;
            break;
        case 1:
            return 80;
            break;
        default:
            break;
    }
    return 20;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 20;
    }else{
        return 0;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 1) {
        return 100;
    }else{
        return 0;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 1) {
        UIView *view = [[UIView alloc]initWithFrame:self.tableView.tableFooterView.bounds];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(20, 50, kHTScreenWidth - 40, kWidth(55)/4.0*3);
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 4;
        button.backgroundColor = kBlueColor;
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitle:@"提交" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(didCommit) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:button];
        return view;
    }
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:tableView.tableHeaderView.bounds];
    view.backgroundColor = kBackgroundColor;
    return view;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        HTNormalTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:normalTitleCell forIndexPath:indexPath];
        cell.normalModel = self.dataSource[indexPath.row];
        return cell;
    }
    HTNormalCell *cell = [tableView dequeueReusableCellWithIdentifier:normalCell forIndexPath:indexPath];
    cell.normalModel = [HTNormalModel normalModelWithTitle:@"行驶证" height:80 imageName:@"bg_license_car"];
    cell.imageWidth.constant = 90;
    self.headImageView = cell.rightImageView;
    [self.headImageView sd_setImageWithURL:[NSURL URLWithString:self.mineModel.license] placeholderImage:[UIImage imageNamed:@"bg_license_car"]options:SDWebImageRefreshCached];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0://车牌类型
            {
                HTChoseViewController *chose = [[HTChoseViewController alloc]init];
                chose.type = ChoseTypeCard;
                chose.delegate = self;
                [self.navigationController pushViewController:chose animated:YES];
            }
                break;
            case 1://车牌号码
            {
                HTTruckLicenseView *license =  [[HTTruckLicenseView alloc]init];
                license.delegate = self;
                [license showView];
            }
                break;
            case 2://车型
            {
                HTChoseViewController *chose = [[HTChoseViewController alloc]init];
                chose.type = ChoseTypeTruck;
                chose.delegate = self;
                [self.navigationController pushViewController:chose animated:YES];
            }
                break;
            case 3://车长
            {
                HTChoseViewController *chose = [[HTChoseViewController alloc]init];
                chose.type = ChoseTypeLength;
                chose.delegate = self;
                [self.navigationController pushViewController:chose animated:YES];
            }
                break;
            case 4://载重
            {
                HTInputViewController *input = [[HTInputViewController alloc]init];
                input.type = InputTypeHeavy;
                input.delegate = self;
                [self.navigationController pushViewController:input animated:YES];
            }
                break;
            default:
                break;
        }
    }
  
   if(indexPath.section == 1){
        [UIAlertController actionSheetStyleShowInController:self title:@"温馨提示" message:@"请上传车辆真实行驶证" alertActionsBlock:^(NSMutableArray<UIAlertAction *> *alertActions) {
            [alertActions addObject:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //初始化UIImagePickerController
                UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
                PickerImage.view.tag = 111;
                PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                PickerImage.allowsEditing = YES;
                //自代理
                PickerImage.delegate = self;
                //页面跳转
                [self presentViewController:PickerImage animated:YES completion:nil];
            }]];
            [alertActions addObject:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
                UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
                PickerImage.view.tag = 111;
                PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
                PickerImage.allowsEditing = YES;
                PickerImage.delegate = self;
                [self presentViewController:PickerImage animated:YES completion:nil];
            }]];
            [alertActions addObject:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        } completion:^{
            
        }];
   }
}
#pragma mark --
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.tableView)
    {
        CGFloat sectionHeaderHeight = 20; //sectionHeaderHeight
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}
#pragma mark --- delegate
- (void)didChoseItem:(NSString *)itemStr withType:(ChoseType)type{
    switch (type) {
        case ChoseTypeTruck:
        {
            HTNormalTitleCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
            cell.detialLabel.text = itemStr;
            self.truckType = itemStr;
        }
            break;
        case ChoseTypeLength:
        {
            HTNormalTitleCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
            cell.detialLabel.text =  [NSString stringWithFormat:@"%@米",itemStr];
            self.length = itemStr;
        }
            break;
        case ChoseTypeCard:
        {
            HTNormalTitleCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
            cell.detialLabel.text = itemStr;
            self.cardType =[itemStr isEqualToString:@"蓝色车牌"] ? @"1":@"2";
        }
            break;
        default:
            break;
    }
}

- (void)didInputMessage:(NSString *)message withType:(InputType)type{
    if (type == InputTypeHeavy) {//载重
        HTNormalTitleCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:0]];
        cell.detialLabel.text =[NSString stringWithFormat:@"%@吨",message];
        self.heavy = message;
    }
}
//车牌号
- (void)didGotCallBackLicense:(NSString *)title{
    HTNormalTitleCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    cell.detialLabel.text = title;
    self.license = title;
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //定义一个newPhoto，用来存放我们选择的图片。
    UIImage *newPhoto = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    self.headImageView.image = newPhoto;
    [self netUpLoadPictureType:@"drivercar" image:newPhoto];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

#pragma mark --- 网络请求
- (void)didCommit{
    if (self.cardType == nil || self.cardType.length <= 0) {
        [HTShowUtil showMessage:@"请选择车牌类型"];
        return;
    }
    if (self.license == nil || self.license.length <= 0) {
        [HTShowUtil showMessage:@"请输入车牌号码"];
        return;
    }
    if (self.truckType == nil || self.truckType.length <= 0) {
        [HTShowUtil showMessage:@"请选择车型"];
        return;
    }
    if (self.length == nil || self.length.length <= 0) {
        [HTShowUtil showMessage:@"请选择车长"];
        return;
    }
    if (self.heavy == nil || self.heavy.length <= 0) {
        [HTShowUtil showMessage:@"请输入载重"];
        return;
    }
    if (self.picurl == nil || self.picurl.length <= 0) {
        [HTShowUtil showMessage:@"请上传行驶证照片"];
        return;
    }
    [self netLoadChangeCar];
}
- (void)netLoadChangeCar{
    [self startHud];
    [HTHttpRequestManager requestChangeCarWithCartype:self.cardType carnumber:self.license carwm:self.truckType carlength:self.length goas:self.heavy isfollow:@"1" success:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"变更车辆：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"变更车辆失败"];
            return;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:@"变更车辆失败"];
            return;
        }
        for (UIViewController * controller in self.navigationController.viewControllers) {
            if ([controller isKindOfClass:[HTMineViewController class]]) {
                [self.navigationController popToViewController:controller animated:YES];
                return;
            }
        }
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
        [HTShowUtil showMessage:@"变更车辆失败"];
    }];
}
- (void)netUpLoadPictureType:(NSString *)type image:(UIImage *)image{
    [self startHud];
    [HTHttpRequestManager requestUploadPictureWithType:type image:image success:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"上传图片：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"图片保存失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:@"图片保存失败"];
            return;
        }
        self.picurl = @"-----";
        [HTShowUtil showMessage:@"图片保存成功"];
        
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
        [HTShowUtil showMessage:@"图片保存失败"];
    }];
}
@end
